package org.xg.study.boot.common.aop;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.xg.study.boot.common.logs.CodeBookLogger;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

/**
 * @author CMG
 * @version 1.0
 * @cLassName LogAspect
 * @description
 * @date 2021/8/26 10:22
 **/
@Aspect
@Component
public class LogAspect {
    protected CodeBookLogger log = new CodeBookLogger(LogAspect.class);

    @Pointcut("execution(public * org.xg.study.boot.controller..*.*(..))")
    public void log() {
    }


    @Around(value = "log()")
    public Object doAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        long startTime = System.currentTimeMillis();
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        // 记录下请求内容
        log.info(10100015,"请求地址URL为: {%s} ,请求方法HTTP_METHOD为: {%s}, 请求IP地址为: {%s} ,请求body为:{%s}", request.getRequestURL().toString(), request.getMethod(), request.getLocalAddr(), proceedingJoinPoint.getArgs());
        Enumeration<String> enu = request.getParameterNames();
        while (enu.hasMoreElements()) {
            String name = (String) enu.nextElement();
            log.info(10100016,"请求name:{%s},value:{%s}", name, request.getParameter(name));
        }
        Object obj = proceedingJoinPoint.proceed();
        log.info(10100017,"响应结果 : {%s} ", obj);
        long endTime = System.currentTimeMillis();
        long differentTime = endTime - startTime;
        log.info(10100018,"请求地址URL为: {%s} ,操作耗时: {%s}ms,请求方法HTTP_METHOD为: {%s}, 请求IP地址为: {%s} ,请求body为:{%s}", request.getRequestURL().toString(), differentTime, request.getMethod(), request.getLocalAddr(), proceedingJoinPoint.getArgs());
        return obj;
    }
}
